﻿using System;
using System.Data;
using System.Text;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Openfree.Framework.DataAccess;

public partial class PMSWeb_CostBillEdit : PMSBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.TableName = "PMS_CostBillItem";
        this.Key = "BillID";
        if (!IsPostBack)
        {
            string cmdText = @"select * from(
                select RTrim(lTrim(HouseNo)) HouseNo from PMS_Customer where HouseNo<>'' group by HouseNo 
                )z order by z.HouseNo asc";
            DataSet ds = BaseAccess.GetDataSet(base.Connection, cmdText);
            cbHouseNo.DataSource = ds.Tables[0];
            cbHouseNo.DataTextField = "HouseNo";
            cbHouseNo.DataValueField = "HouseNo";
            cbHouseNo.DataBind();

            if (string.IsNullOrEmpty(Request[this.Key]))
            {
                hfAddOrEdit.Value= "Add";
                hfBillID.Value = Guid.NewGuid().ToString();
                tbBillDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
            }
            else
            {
                hfAddOrEdit.Value= "Edit";
                hfBillID.Value = Request[this.Key];
                hfBillID.Value =  hfBillID.Value.Replace("'","");

                cmdText = "select * from PMS_CostBill where BillID='{0}'";
                cmdText = string.Format(cmdText, hfBillID.Value);
                DataSet dsCostBill = BaseAccess.GetDataSet(base.Connection, cmdText);
                DataRow rowCostBill = dsCostBill.Tables[0].Rows[0];
                tbSubject.Text = rowCostBill["Subject"].ToString();
                tbBillDate.Text = DateTime.Parse(rowCostBill["BillDate"].ToString()).ToString("yyyy-MM-dd");


                cmdText = "select distinct HouseNo from PMS_CostBillItem";
                ds = BaseAccess.GetDataSet(base.Connection, cmdText);
                foreach (ListItem item in cbHouseNo.Items)
                {
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        if (item.Value == row["HouseNo"].ToString())
                        {
                            item.Selected = true;
                            break;
                        }
                    }
                }
            }
            pnlGrid.Visible = false;
            pnlEdit.Visible = true;
            
            
        }
        else
        {
            if(this.pnlGrid.Visible)
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
        }
    }
   
    protected void FillGirdView(int currentPage, string cmdText)
    {
        if (string.IsNullOrEmpty(cmdText))
        {
            cmdText = ViewState[this.ClientID + "cmdText"].ToString();
        }
        SqlSplitPage splitPage = new SqlSplitPage(base.Connection, cmdText);
        splitPage.PageSize = 10;
        DataSet ds = splitPage.LoadDataSet(currentPage);
        //成功查询出数据后缓存
        ViewState[this.ClientID + "cmdText"] = cmdText;
        gridView.ShowFooter = true;
        gridView.NavigationData = splitPage.GetNavigationData(currentPage);
        gridView.DataSource = ds.Tables[0];
        gridView.DataBind();
    }

    protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            DataSet dsCostItem =  SessionManager.DataSet;

            e.Row.Cells[0].Text = "是否收费";
            e.Row.Cells[1].Text = "楼号/区域";
            e.Row.Cells[2].Text = "房间号";
            e.Row.Cells[3].Text = "联系电话";
            for(int i=4; i<e.Row.Cells.Count; i++)
            {
                foreach(DataRow row in dsCostItem.Tables[0].Rows)
                {
                    if (row["CostID"].ToString() == e.Row.Cells[i].Text.Replace("Col_", ""))
                    {
                        e.Row.Cells[i].Text = row["Subject"].ToString() +
                            "(" + row["Cycle"].ToString() + ")";
                        break;
                    }
                }
            }
        }
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //组建命名规则  楼号区域_房间号_cb/tb列字段
            DataSet dsCostItem = SessionManager.DataSet;
           
            string cmdText = "HouseNo='{0}' and RoomNo='{1}'";
            cmdText = string.Format(cmdText, e.Row.Cells[1].Text, e.Row.Cells[2].Text);
            DataRow[] rows = SessionManager.DataSetDetail.Tables[0].Select(cmdText);

            
            
            if(rows.Length>0)
            {
                e.Row.Cells[0].Text = string.Format("<input id=\"{0}\" name=\"{0}\" type=\"checkbox\" checked=\"checked\" />",
                    e.Row.Cells[1].Text + "_" + e.Row.Cells[2].Text + "_cbSelected");
            }
            else
            {
                e.Row.Cells[0].Text = string.Format("<input id=\"{0}\" name=\"{0}\" type=\"checkbox\"/>",
                    e.Row.Cells[1].Text + "_" + e.Row.Cells[2].Text + "_cbSelected");
            }

            for (int i = 4; i < e.Row.Cells.Count; i++)
            {
                string costID = SessionManager.DataSet.Tables[0].Rows[i - 4]["CostID"].ToString();
                cmdText = "HouseNo='{0}' and RoomNo='{1}' and CostID='{2}'";
                cmdText = string.Format(cmdText, e.Row.Cells[1].Text, e.Row.Cells[2].Text, costID);
                rows = SessionManager.DataSetDetail.Tables[0].Select(cmdText);

                foreach (DataRow row in dsCostItem.Tables[0].Rows)
                {
                    if (row["CostID"].ToString() == e.Row.Cells[i].Text.Replace("Col_", ""))
                    {
                        string input = "<input id=\"{0}\" name=\"{0}\" type=\"checkbox\" [IsSelected] />" +
                            "<input id=\"{1}\" name=\"{1}\" type=\"text\" value=\"[Money]\" style=\"width:50px\" />" ;

                        input = string.Format(input, e.Row.Cells[1].Text + "_" + e.Row.Cells[2].Text + "_" + "cb"+row["CostID"].ToString(),
                            e.Row.Cells[1].Text + "_" + e.Row.Cells[2].Text + "_" + "tb" + row["CostID"].ToString());

                        if (rows.Length > 0)
                        {
                            //缓存优先级高
                            if (Boolean.Parse(rows[0]["IsSelected"].ToString()))
                            {
                                string money = string.IsNullOrEmpty(rows[0]["Money"].ToString()) ? "" :
                                    Convert.ToDouble(rows[0]["Money"].ToString()).ToString("###,###,###.00");
                                if (money == ".00") money = "";
                                input = input.Replace("[Money]", money);
                            }
                            else
                            {
                                input = input.Replace("[Money]", "");
                            }
                        }
                        else
                        {
                            //缓存没有数据，根据配置情况设置
                            string money = Convert.ToDouble(row["Money"].ToString()).ToString("###,###,###.00");
                            if (money == ".00") money = "";
                            input = input.Replace("[Money]", money);
                        }


                        if (rows.Length > 0)
                        {
                            //缓存优先级高
                            if (Boolean.Parse(rows[0]["IsSelected"].ToString()))
                            {
                                input = input.Replace("[IsSelected]", "checked=\"checked\"");
                            }
                            else
                            {
                                input = input.Replace("[IsSelected]", "");
                            }
                        }
                        else if (row["IsSelected"].ToString() == "True")
                        {
                            //缓存没有数据，根据配置情况设置
                            input = input.Replace("[IsSelected]", "checked=\"checked\"");
                        }
                        else
                        {
                            input = input.Replace("[IsSelected]", "");
                        }

                        e.Row.Cells[i].Text = input ;
                        break;
                    }
                }

            }
        }
    }

    protected void gridView_SplitPageIndexChange(object sender, CommandEventArgs e)
    {
        SaveCurrentPageData();
        FillGirdView(Int32.Parse(e.CommandArgument.ToString()), ViewState[this.ClientID + "cmdText"].ToString());
    }

    private void SaveCurrentPageData()
    {
        //缓存本页数据
        foreach (GridViewRow row in gridView.Rows)
        {
            string crlID = row.Cells[1].Text + "_" + row.Cells[2].Text + "_cbSelected";
            if (string.IsNullOrEmpty(Request[crlID]))
            {
                //整行数据删除
                string cmdText = "HouseNo='{0}' and RoomNo='{1}'";
                cmdText = string.Format(cmdText, row.Cells[1].Text, row.Cells[2].Text);
                DataRow[] rows = SessionManager.DataSetDetail.Tables[0].Select(cmdText);
                for (int i = 0; i < rows.Length; i++)
                {
                    SessionManager.DataSetDetail.Tables[0].Rows.Remove(rows[i]);
                }
                //SessionManager.DataSetDetail.AcceptChanges();
                continue;
            }

            for (int i = 4; i < row.Cells.Count; i++)
            {
                string costID = SessionManager.DataSet.Tables[0].Rows[i - 4]["CostID"].ToString();
                string cmdText = "HouseNo='{0}' and RoomNo='{1}' and CostID='{2}'";
                cmdText = string.Format(cmdText, row.Cells[1].Text, row.Cells[2].Text, costID);
                DataRow[] rows = SessionManager.DataSetDetail.Tables[0].Select(cmdText);

                //本列字段是否钩选
                crlID = row.Cells[1].Text + "_" + row.Cells[2].Text + "_cb" + costID;
                bool isSelect = true;
                if (string.IsNullOrEmpty(Request[crlID]))
                {
                    //本列没有钩选
                    isSelect = false;
                }

                crlID = row.Cells[1].Text + "_" + row.Cells[2].Text + "_tb" + costID;
                double value = 0;
                if (rows.Length == 0)
                {
                    DataRow newRow = SessionManager.DataSetDetail.Tables[0].NewRow();
                    newRow["BillItemID"] = Guid.NewGuid().ToString();
                    newRow["BillID"] = hfBillID.Value;
                    newRow["CostID"] = costID;
                    newRow["HouseNo"] = row.Cells[1].Text;
                    newRow["RoomNo"] = row.Cells[2].Text;
                    newRow["Telephone"] = row.Cells[3].Text.Trim();
                    if (string.IsNullOrEmpty(Request[crlID]))
                    {
                        newRow["Money"] =DBNull.Value;
                    }
                    else if(double.TryParse(Request[crlID].Trim(), out value))
                    {
                        newRow["Money"] = value;
                    }
                    else
                    {
                        newRow["Money"] = DBNull.Value;
                    }
                    newRow["IsSelected"] = isSelect;
                    newRow["CreateDate"] = DateTime.Now;
                    newRow["UserID"] = SessionManager.UserID;

                    SessionManager.DataSetDetail.Tables[0].Rows.Add(newRow);
                }
                else
                {
                    DataRow newRow = rows[0];
                    newRow["BillItemID"] = Guid.NewGuid().ToString();
                    newRow["BillID"] = hfBillID.Value;
                    newRow["CostID"] = costID;
                    newRow["HouseNo"] = row.Cells[1].Text;
                    newRow["RoomNo"] = row.Cells[2].Text;
                    newRow["Telephone"] = row.Cells[3].Text.Trim();
                    if (string.IsNullOrEmpty(Request[crlID]))
                    {
                        newRow["Money"] = DBNull.Value;
                    }
                    else if (double.TryParse(Request[crlID].Trim(), out value))
                    {
                        newRow["Money"] = value;
                    }
                    else
                    {
                        newRow["Money"] = DBNull.Value;
                    }
                    newRow["IsSelected"] = isSelect;
                    newRow["CreateDate"] = DateTime.Now;
                    newRow["UserID"] = SessionManager.UserID;
                }
            }
        }
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        SaveCurrentPageData();
        pnlGrid.Visible = false;
        pnlEdit.Visible = true;
    }

    protected void btnRemove_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(Request["CostID"]))
        {
            base.Alert("请选择一条记录");
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
            return;
        }
        PMSAccess.RemoveDataRow(this.TableName, this.Key, Request["CostID"].ToString());

        FillGirdView(this.gridView.SplitPageIndex, string.Empty);
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        SaveCurrentPageData();


        if (hfAddOrEdit.Value == "Add")
        {
            string cmdText = "select * from PMS_CostBill where 1=2";
            cmdText = string.Format(cmdText, hfBillID.Value);
            DataSet dsCostBill = BaseAccess.GetDataSet(base.Connection, cmdText, "PMS_CostBill");
            DataRow rowCostBill = dsCostBill.Tables[0].NewRow();
            rowCostBill["BillID"] = hfBillID.Value;
            rowCostBill["Subject"] = tbSubject.Text.Trim();
            rowCostBill["BillDate"] = tbBillDate.Text.Trim();
            rowCostBill["CreateDate"] = DateTime.Now;
            rowCostBill["UserID"] = SessionManager.UserID;
            dsCostBill.Tables[0].Rows.Add(rowCostBill);

            BaseAccess.UpdateDataSet(base.Connection, "PMS_CostBill", dsCostBill);

        }
        else
        {
            string cmdText = "select * from PMS_CostBill where BillID='{0}'";
            cmdText = string.Format(cmdText, hfBillID.Value);
            DataSet dsCostBill = BaseAccess.GetDataSet(base.Connection, cmdText, "PMS_CostBill");
            DataRow rowCostBill = dsCostBill.Tables[0].Rows[0];
            rowCostBill["Subject"] = tbSubject.Text.Trim();
            rowCostBill["BillDate"] = tbBillDate.Text.Trim();

            BaseAccess.UpdateDataSet(base.Connection, "PMS_CostBill", dsCostBill);
        }

        BaseAccess.UpdateDataSet(base.Connection, "PMS_CostBillItem", SessionManager.DataSetDetail);
        //不能删除，删除了修改收费单时会造成没有参考标记
        //BaseAccess.ExecuteNonQuery(base.Connection, "delete from PMS_CostBillItem where IsSelected=0");

        Response.Redirect("CostBill.aspx");
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("CostBill.aspx");
    }

    protected void btnNext_Click(object sender, EventArgs e)
    {
        string hoseNO = string.Empty;
        foreach(ListItem item in cbHouseNo.Items)
        {
            if(item.Selected)
            {
                hoseNO += "'" + item.Value + "',"; 
            }
        }
        if(hoseNO == string.Empty)
        {
            base.Alert("请选择一条记录");
            return;
        }

        pnlGrid.Visible = true;
        pnlEdit.Visible = false;


        //动态生成表格各列
        string cmdText = "select * from PMS_CostItem where IsUsed=1 and IsDeleted=0 order by OrderIndex";
        string column = string.Empty;
        DataSet dsCostItem = BaseAccess.GetDataSet(base.Connection, cmdText);
        SessionManager.DataSet = dsCostItem;
        foreach (DataRow row in dsCostItem.Tables[0].Rows)
        {
            //前缀防止与 PMS_Customer 表默认字段冲突
            column += ", '" + row["CostID"].ToString() + "' Col_" + row["CostID"].ToString();
        }

        cmdText = @"select 1 IsSelected, RTrim(LTrim(HouseNo)) HouseNo, RTrim(LTrim(RoomNo)) RoomNo,  
                    RTrim(LTrim(Telephone)) Telephone
                    {0} from PMS_Customer where HouseNo in ({1})";
        hoseNO = hoseNO.TrimEnd(',');
        cmdText = string.Format(cmdText, column, hoseNO);

        

        //取出数据，提供修改数据的缓存记录容器
        string cmdText2 = "select * from PMS_CostBillItem where BillID='{0}'";
        cmdText2 = string.Format(cmdText2, hfBillID.Value);
        SessionManager.DataSetDetail = BaseAccess.GetDataSet(base.Connection, cmdText2, "PMS_CostBillItem");


        FillGirdView(0, cmdText);
    }

}
